<!--
  * 授权表单
-->
<template>
  <a-modal
    :title="formData.id ? '商家授权' : '添加商家授权'"
    :width="1000"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'">
      <div>
        <p>请登录支付宝开放平台/控制台/商家授权，添加商家授权码。注：只添加已生效数据</p>
        <p>链接：https://open.alipay.com/develop/isv/sub/merchant-authorize?appId=2021005127672875</p>
      </div>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="授权商家名称" name="companyName">
            <CustomSelect
              v-model:value="formData.companyName"
              :placeholder="'请选择授权商家名称'"
              :api="merchantApi.page"
              queryParamKey="companyNameLeftLike"
              @change="(...value) => changeCompanyName(value)"
              valueField="companyName"
              labelField="companyName,no"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 授权商家账户" name="merchantId">
            <a-input v-model:value="formData.merchantId" disabled placeholder="请输入授权商家账户" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 应用名称" name="appName">
            <a-input v-model:value="formData.appName" placeholder="请输入应用名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 应用码" name="appCode">
            <a-input v-model:value="formData.appCode" placeholder="请输入应用码" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="授权应用id(appid)" name="appId">
            <a-input v-model:value="formData.appId" placeholder="请输入授权应用id(appid)" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 应用类型" name="appType">
            <a-select placeholder="请选择应用类型" v-model:value="formData.appType" :options="APP_TYPE" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 授权产品" name="authAppArr">
            <a-select placeholder="请选择授权产品" v-model:value="formData.authAppArr" mode="multiple" :options="AUTH_APP" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 授权token" name="appAuthToken">
            <a-input v-model:value="formData.appAuthToken" placeholder="请输入授权token" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template></a-modal
  >
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api'
  import { appAuthUpdate, appAuthInsert, appAuthFindId } from '/@/api/business/b-operation/merchant-app/app-auth-api'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { strToArr } from '/@/utils/common'
  import {
    AUTH_APP, //授权产品，产品列表
    APP_TYPE, ///应用类型
  } from '/@/constants/dict'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await appAuthFindId(data)
      formData.value = { ...res.data, authAppArr: strToArr(res.data.authApp) }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }
  /* 切换商家 */
  function changeCompanyName(data) {
    if (!data[1][0]) {
      formData.value.merchantId = undefined
      return
    }
    formData.value.merchantId = data[1][0].id
  }
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    companyName: undefined,
    merchantId: undefined,
    appName: undefined,
    appCode: undefined,
    appId: undefined,
    appType: undefined,
    authAppArr: [],
    authApp: undefined,
    id: undefined,
    appAuthToken: undefined,
  }

  let formData = ref({ ...formDefault })

  const rules = {
    companyName: [{ required: true, message: '授权商家名称 必填' }],
    merchantId: [{ required: true, message: '授权商家账户 必填' }],
    appName: [{ required: true, message: '应用名称 必填' }],
    appCode: [{ required: true, message: '应用码 必填' }],
    appId: [{ required: true, message: '授权应用id(appid) 必填' }],
    appType: [{ required: true, message: '应用类型 必填' }],
    authAppArr: [{ required: true, message: '授权产品 必填' }],
    appAuthToken: [{ required: true, message: '授权token 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value, authApp: formData.value.authAppArr.toString() }
      if (formData.value.id) {
        await appAuthUpdate(data)
      } else {
        await appAuthInsert(data)
      }
      message.success('操作成功')
      emits('ok')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.formType == 'add' && props.rowData?.applicationId) {
        formData.value.applicationId = props.rowData.applicationId
      }
      if (props.open && props.rowData && props.formType != 'add') {
        getFormData(val[0])
      }
    },
    { immediate: true },
  )
</script>
